/*
 * @Author: yangzonglong
 * @Date: 2021-03-05 12:08:36
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-30 16:05:58
 * @Auditor:
 */
import React, { useState, useImperativeHandle, forwardRef, useEffect } from 'react';
import { DatePicker } from 'antd-mobile';
import Icon from './icon/Icon';
import RequiredMark from './RequiredMark';
import moment from 'moment';

const divStyle = {
  border: '1px solid rgba(35, 37, 40, 0.1)',
  padding: '12px 14px',
  fontSize: '14px',
  height: '45px',
  position: 'relative',
  lineHeight: '19px',
};
const iconStyle = {
  position: 'absolute',
  right: '15px',
  fontSize: '14px',
};

const defaultFormat = 'YYYY/MM/DD';

const transferObj = {
  'YYYY/MM/DD': 'YYYY/MM/DD',
  'YYYY/MM/DD HH:mm:ss': 'YYYY/MM/DD HH:mm',
};

const App = (props, ref) => {
  const { disabled, formItemProps, datePickerProps } = props;
  const [value, setValue] = useState(undefined);

  useImperativeHandle(ref, () => ({
    getData: () => value && moment(value).format(datePickerProps?.format ? transferObj[datePickerProps.format] : defaultFormat),
  }));

  useEffect(() => {
    if (props.initialValue) setValue(new Date(props.initialValue));
  }, [props.initialValue]);

  return (
    <DatePicker
      mode={datePickerProps?.format ? (datePickerProps.format === defaultFormat ? 'date' : 'datetime') : 'date'}
      disabled={disabled}
      value={value}
      onOk={setValue}
    >
      <div className="am-list-item am-input-item am-list-item-middle">
        <div className="am-list-line">
          <div className="am-input-label am-input-label-5">
            {
              <span>
                {formItemProps?.required && <RequiredMark />}
                {formItemProps?.label}
              </span>
            }
          </div>
          <div style={divStyle}>
            {value ? (
              moment(value).format(datePickerProps?.format ? transferObj[datePickerProps.format] : defaultFormat)
            ) : (
              <span style={{ color: '#bbb' }}>{datePickerProps?.placeholder || ''}</span>
            )}
            <Icon icon="&#xe668;" style={iconStyle} />
          </div>
        </div>
      </div>
    </DatePicker>
  );
};

export default forwardRef(App);
